package com.bskj.kuaifu.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.bskj.common.bean.model.ParkInfo;
import com.bskj.common.utils.Global;
import com.bskj.common.utils.HttpRequestUtil;
import com.bskj.common.utils.LogUtils;
import com.bskj.common.utils.ResultMapUtil;
import com.bskj.common.utils.StringUtils;
import com.bskj.common.web.BaseController;
import com.bskj.kuaifu.service.IParkInfoService;
import com.bskj.kuaifu.service.IPayInfoService;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;

@Controller
@RequestMapping("/pay")
public class PayController extends BaseController {
	@Autowired
	private WXPay wxPay;

	@Resource(name = "myAmqpTemplate")
	private AmqpTemplate amqpTemplate;

	@Autowired
	private IPayInfoService payInfoService;
	
	@Autowired
	private IParkInfoService parkInfoService;
	
	@RequestMapping("recharge/index")
	public ModelAndView payIndex() throws Exception {
		ModelAndView mv = new ModelAndView();

		return mv;
	}
	
	@ResponseBody
	@RequestMapping("cmbcNotify")
	public String cmbcNotify(HttpServletRequest request) {
		Map map = request.getParameterMap();
		for(Object key : map.keySet()) {
			System.out.println("key : " + key + "   value : " + map.get(key));
		}
		return "ok";
	}
	
	
	
	@ResponseBody
	@RequestMapping("wxBalanceReturn")
	public String wxBalanceReturn(HttpServletRequest request) {
		try {
			String xmlStr = getXmlStrFromRequest(request);
			Map<String, String> resultMap = wxPay.processResponseXml(xmlStr);
			String return_code = resultMap.get("return_code");
			if (return_code.equals(WXPayConstants.SUCCESS)) {
				byte[] bodys = xmlStr.getBytes("UTF-8");
				MessageProperties properties = new MessageProperties();
				properties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
				Message message = new Message(bodys, properties);
				amqpTemplate.send("payInfoKey", message);
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtils.debug(e.getMessage());
		}
		return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
	}

 	/**
	 * 微信统一下单
	 *
	 * @param openId
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("unifiedorder")
	public Map<String, Object> unifiedorder(String appId, String openId, int userId, int totalFee) throws Exception {

		Map<String, String> resultMap = null;
		try {
			String ip = HttpRequestUtil.getIp(getRequest());
			String notifyUrl = Global.getConfig("WX_NOTIFY_URL");
			resultMap = payInfoService.unifiedOrder(appId, openId, userId, totalFee, ip, notifyUrl);
			if (StringUtils.isBank(resultMap.get("error"))) {
				return ResultMapUtil.genDefaultSuccessDataMap(resultMap.get("wxPayParams"));
			} else {
				return ResultMapUtil.genErrorMap(resultMap.get("error"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultMapUtil.genErrorMap("下单失败,请重试");
		}

	}
	
	/**
	 * 无牌车支付下单
	 *
	 * @param openId
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("noCarnoUnifiedorder")
	public Map<String, Object> unifiedorder(String appId, String openId,Integer parkId) throws Exception {

		Map<String, String> resultMap = null;
		try {
			String ip = HttpRequestUtil.getIp(getRequest());
			String notifyUrl = Global.getConfig("NO_CARNO_WX_NOTIFY_URL");
			resultMap = payInfoService.noCarnoUnifiedOrder(appId, openId, parkId, ip, notifyUrl);
			LogUtils.debug("resultMap : " + resultMap);
			if (StringUtils.isBank(resultMap.get("error"))) {
				return ResultMapUtil.genDefaultSuccessDataMap(resultMap.get("wxPayParams"));
			} else {
				return ResultMapUtil.genErrorMap(resultMap.get("error"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultMapUtil.genErrorMap("下单失败,请重试");
		}

	}
	
	/**
	 * 无牌车支付回调
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("noCarnoWxPayNotify")
	public String noCarnoWxPayNotify(HttpServletRequest request) {
		try {
			String xmlStr = getXmlStrFromRequest(request);
			LogUtils.info("noCarnoWxPayNotify notify : " + xmlStr);
			JSONObject resp = JSONObject.parseObject(xmlStr);
			String return_code = resp.getString("state");
			if (!StringUtils.isBank(return_code) && return_code.equals("00")) {
				byte[] bodys = xmlStr.getBytes("UTF-8");
				MessageProperties properties = new MessageProperties();
				properties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
				Message message = new Message(bodys, properties);
				amqpTemplate.send("noCarnoPayInfokey", message);
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtils.debug(e.getMessage());
		}
		return "ok";
	}

	/**
	 * 支付欠费订单的回调
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("wxArrearsReturn")
	public String wxArrearsReturn(HttpServletRequest request) {
		try {
			String xmlStr = getXmlStrFromRequest(request);
			Map<String, String> resultMap = wxPay.processResponseXml(xmlStr);
			String return_code = resultMap.get("return_code");
			if (return_code.equals(WXPayConstants.SUCCESS)) {
				byte[] bodys = xmlStr.getBytes("UTF-8");
				MessageProperties properties = new MessageProperties();
				properties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
				Message message = new Message(bodys, properties);
				amqpTemplate.send("arrearInfoKey", message);
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtils.debug(e.getMessage());
		}
		return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
	}
	
	/**
	 * 无感支付回调
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("noSenseNotify")
	public String noSenseNotify(HttpServletRequest request) throws Exception{
		String str = HttpRequestUtil.getXmlStrFromRequest(request);
    	LogUtils.debug("noSenseNotify notify : " + str);
    	//更新用户和绑定的车牌信息
    	JSONObject jsonObj = JSONObject.parseObject(str);
//    	String openid = jsonObj.getString("openid");
    	String outTradeNo = jsonObj.getString("outTradeNo");
    	ParkInfo parkInfo = parkInfoService.getParkInfo(outTradeNo);
    	if(parkInfo == null) {
    		LogUtils.error("outTradeNo : " + outTradeNo + " not find parkInfo!!!!");
    	} else {
//    		String carNo = parkInfo.getCarNo();
//    		ParkingLotCustomer lot = parkingLotCustomerService.get(parkInfo.getParkLotCustimerId());
//    		if(lot != null) {
//    			userInfoService.updateUserAndCarInfo(lot.getAppid(), openid, carNo);
//    		}
    	}
		return "ok";
	}

	private String getXmlStrFromRequest(HttpServletRequest request) throws IOException {
		String result = "";
		InputStream inStream = request.getInputStream();
		int _buffer_size = 1024;
		if (inStream != null) {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] tempBytes = new byte[_buffer_size];
			int count = -1;
			while ((count = inStream.read(tempBytes, 0, _buffer_size)) != -1) {
				outStream.write(tempBytes, 0, count);
			}
			tempBytes = null;
			outStream.flush();
			//将流转换成字符串
			result = new String(outStream.toByteArray(), "UTF-8");
			LogUtils.debug("result:" + result);
		}
		return result;
	}
}
